import { ref, onMounted, reactive } from "vue";
import type { PaginationProps, LoadingConfig } from "@pureadmin/table";
import {
  getArticleList,
  updateArticleTop,
  revertArticle,
  deleteArticle,
  getArticleById,
  type ArticleForm
} from "@/api/blog/article";
import { getCategoryDictionary } from "@/api/blog/category";
import { getTagDictionary } from "@/api/blog/tag";
import { message } from "@/utils/message";

export function useColumns() {
  const isArticlePublishEditorShow = ref(false);
  const param = reactive({
    currentPage: 1,
    pageSize: 10,
    articleTitle: null,
    tagId: null,
    categoryId: null,
    isTop: null,
    status: null
  });
  const editorKey = ref(Date.now());
  const articleForm = reactive<ArticleForm>({
    id: "",
    title: "",
    content: "",
    author: "",
    summary: "", // 文章摘要
    cover: "", //文章封面
    categoryId: null,
    tags: [], // 标签id
    isTop: 2, // 置顶 1 置顶 2 取消置顶
    order: 1, // 置顶文章的排序
    status: 1, // 状态 1 公开 2 私密
    coverList: [],
    tagIdList: []
  });
  const primaryParam = reactive({ ...param });
  const tableImageList = ref([]);
  const tableData = ref([]);
  const categoryOptionList = ref([]);
  const tagOptionList = ref([]);
  const loading = ref(false);
  const tableSize = ref("small");
  const selectList = ref<any>([]);
  const columns: TableColumnList = [
    {
      type: "selection",
      align: "left",
      width: 40
    },
    {
      label: "序号",
      type: "index",
      width: 55
    },
    {
      label: "文章标题",
      prop: "articleTitle",
      minWidth: 130
    },
    {
      label: "作者",
      prop: "author",
      minWidth: 60
    },
    {
      label: "文章描述",
      prop: "summary",
      minWidth: 130
    },
    {
      label: "分类",
      prop: "categoryName",
      cellRenderer: ({ row }) => <el-tag>{row.categoryName}</el-tag>
    },
    {
      label: "标签",
      prop: "tagNameList",
      minWidth: 220,
      cellRenderer: ({ row }) =>
        row.tagNameList.map(tagName => (
          <el-tag style="margin-left: 3px;">{tagName}</el-tag>
        ))
    },
    {
      label: "封面",
      prop: "cover",
      width: 200,
      slot: "image"
    },
    {
      label: "是否置顶",
      prop: "isTop",
      slot: "isTop"
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 80,
      cellRenderer: ({ row }) => (
        <span>{row.status == 1 ? "公开" : "私密"}</span>
      )
    },
    {
      label: "发布日期",
      prop: "createTime"
    },
    {
      label: "修改日期",
      prop: "updateTime"
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  /** 分页配置 */
  const pagination = reactive<PaginationProps>({
    pageSize: 10,
    currentPage: 1,
    pageSizes: [10, 15, 20],
    total: 0,
    align: "right",
    background: true
  });

  /** 加载动画配置 */
  const loadingConfig = reactive<LoadingConfig>({
    text: "正在加载第一页...",
    viewBox: "-10, -10, 50, 50",
    spinner: `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `
    // svg: "",
    // background: rgba()
  });
  // tabChange
  const tabChange = (val: any) => {
    param.status = val.index != 0 ? Number(val.index) : null;
    pageGetArticleList();
  };
  // 搜
  function onSearch() {
    pageGetArticleList();
  }

  // 重置参数
  const resetParam = () => {
    Object.assign(param, primaryParam);
    pageGetArticleList();
  };

  // 修改文章置顶信息
  async function changeTop(val) {
    if (val) {
      const { id, isTop } = val;
      const res = await updateArticleTop(id, 0, isTop);
      if (res) {
        message(`${isTop == 1 ? "置顶" : "取消置顶"} 成功`, {
          type: "success"
        });
      }
    }
  }

  // 恢复文章
  async function revertArticleById(id, articleTitle) {
    if (id) {
      const res = await revertArticle(id);
      if (res) {
        message(`恢复文章 ${articleTitle}成功`, { type: "success" });
      }
      pageGetArticleList();
    }
  }
  // 公开隐藏文章
  async function changeArticlePublic(id, status) {
    const v = status == 1 ? 2 : 1;
    const res = await updateArticleTop(id, 1, v);
    if (res) {
      message(`${status == 1 ? "隐藏" : "公开"} 文章成功`, { type: "success" });
    }
    pageGetArticleList();
  }

  function onSizeChange(val) {
    param.pageSize = val;
    pageGetArticleList();
  }

  function onCurrentChange(val) {
    if (typeof val == "number") {
      loadingConfig.text = `正在加载第${val}页...`;
      param.currentPage = val;
      pageGetArticleList();
    }
  }
  async function editArticle(row) {
    // 根据id获取文章详情
    const res = await getArticleById(row.id);
    if (res) {
      const { cover, tags } = res;
      Object.assign(articleForm, res);
      articleForm.id = row.id;
      articleForm.coverList = [
        {
          // 获取数组最后一位有很多种方法 article_cover.split('/').reverse()[0]
          //           article_cover.split('/').slice(-1)
          //           article_cover.split('/').at(-1)
          id: 1,
          name: cover.split("/").pop(),
          url: cover
        }
      ];
      tags.forEach(tagName => {
        articleForm.tagIdList.push(
          tagOptionList.value.find(tag => tag.name == tagName).id
        );
      });
      editorKey.value = Date.now(); // 重新触发组件重建
      isArticlePublishEditorShow.value = true;
    }
  }

  function addArticle() {
    Object.assign(articleForm, {
      id: "",
      title: "",
      author: "",
      content: "",
      summary: "",
      cover: "",
      categoryId: null,
      tags: [],
      isTop: 2,
      order: 1,
      status: 1,
      coverList: [],
      tagIdList: []
    });
    editorKey.value = Date.now(); // 重新触发组件重建
    isArticlePublishEditorShow.value = true;
  }
  // 通过id删除文章
  async function deleteArticleById(id, status, articleTitle) {
    const ids: Array<number> = [];
    ids.push(id);
    const res = await deleteArticle(ids);
    if (res) {
      if (status == 3) {
        message(`删除文章 ${articleTitle}成功`, { type: "success" });
      } else {
        message(`文章 ${articleTitle}已进入回收站`, { type: "success" });
      }
      pageGetArticleList();
    }
  }

  async function deleteBatch() {
    if (selectList.value.length) {
      const list = selectList.value.map(se => se.id);
      const res = await deleteArticle(list);
      if (res) {
        message(`批量删除文章成功`, { type: "success" });
        pageGetArticleList();
      }
    } else {
      message("请先选择文章", { type: "warning" });
    }
  }
  function handleSelectionChange(val) {
    selectList.value = val;
  }

  // 分页获取文章
  async function pageGetArticleList() {
    loading.value = true;
    const res = await getArticleList(param);

    if (res) {
      tableData.value = res.list;
      pagination.total = res.total;
      tableImageList.value = [];
      tableImageList.value = tableData.value.map(v => {
        return v.cover;
      });
    }
    loading.value = false;
  }

  async function getTagOptionVO() {
    const res = await getTagDictionary();
    if (res) {
      tagOptionList.value = res;
    }
  }
  async function getCategoryVO() {
    const res = await getCategoryDictionary();
    if (res) {
      categoryOptionList.value = res;
    }
  }
  onMounted(async () => {
    // 获取文章列表
    await pageGetArticleList();

    // 获取选择列表
    await getCategoryVO();
    await getTagOptionVO();
  });

  return {
    param,
    loading,
    columns,
    tableData,
    tableImageList,
    tableSize,
    pagination,
    loadingConfig,
    tagOptionList,
    categoryOptionList,
    isArticlePublishEditorShow,
    tabChange,
    resetParam,
    onSearch,
    onSizeChange,
    onCurrentChange,
    articleForm,
    editorKey,
    editArticle,
    addArticle,
    deleteArticleById,
    changeTop,
    revertArticleById,
    changeArticlePublic,
    handleSelectionChange,
    deleteBatch
  };
}
